const app = getApp()
import {
  parseTime
} from '../../utils/util'
import {
  decryptData,
  encryptionData
} from '../../utils/public'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    presentStageArr: [
      '待处理',
      '进行中',
      '已完成',
      '已逾期'
    ],
    presentStageSubArr: [
      '此订单还未绑定设备。',
      '订单正在进行中。',
      '该订单已完成。',
      '该订单已逾期，请联系购买者尽快返还设备。'
    ],
    orderNameArray: [
      '设备发放',
      '项目完成',
      '设备押金返还',
      '项目配置',
      '更换设备',
      '预约转诊',
      '开启项目',
      '拒绝接收'
    ],
    order_log: [{
        title: '设备发放',
        created_at: '2020-12-18 16:23:56',
      },
      {
        title: '项目完成',
        created_at: '2020-12-18 16:23:56',
      },
      {
        title: '设备押金返还',
        created_at: '2020-12-18 16:23:56',
      },
    ],
    orderData: null,
    tabNav: 0,
    //蓝牙参数
    BTLTEST: '',
    btnFis: false,
    type: 1,
    deviceId: '',
    UUID1: '', //服务
    UUID2: '', //特征
    serviceId: '',
    characteristicId: '',
    commandEnd: '', //最终指令
    commandStart: '', //最初指令
    deviceNo: '', //设备编号
    orderNo: '', //订单编号
    isLock: null,
    modelid: wx.getStorageSync('modelid')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    this.setData({
      id: options.id,
      tabNav: wx.getStorageSync('tabNav')
    })
    console.log(options.id);
    this.getList()
  },
  getList() {
    let that = this
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    wx.request({
      url: app.globalData.serverUrl + '/ddOrder/detail/' + that.data.id,
      method: 'GET',
      header: {
        'token': wx.getStorageSync('token')
      },
      success: (res => {
        let resData = res.data
        if (resData.code == 200) {
          console.log(resData.data.order);
          if (resData.data.order.orderHistoryList.length > 0) {
            resData.data.order.orderHistoryList.map((item, index) => {
              item.text = that.data.orderNameArray[item.orderStatus]
              item.created_at = parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}:{s}')
              item.content = that.data.tabNav == 1 ? resData.data.order.configurationName : ''
            })
            resData.data.order.deviceReturnTime = parseTime(resData.data.order.deviceReturnTime, '{m}月{d}日')
            resData.data.order.configurationTimeNew = parseTime(resData.data.order.configurationTime, '{y}-{m}-{d} {h}:{i}:{s}')
            resData.data.order.configurationTime = parseTime(resData.data.order.configurationTime, '{m}月{d}日')
          }
          that.setData({
            orderData: resData.data.order
          })
          wx.hideLoading()
        }
      })
    })
  },

  showDialog({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialog').show()
  },
  shouquan() {
    wx.openSetting()
  },
  showDialogsq({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialogsq').show()
  },
  colsFun() {
    wx.navigateBack({
      delta: 1,
    })
    // wx.reLaunch({
    //   url: '/pages/workbench/workbench',
    // })
  },
  createBLEConnection(deviceId) {
    let that = this
    wx.showLoading({
      title: '设备搜索中',
      mask: true
    })
    let trimA = setTimeout(() => {
      wx.closeBLEConnection()
      wx.closeBluetoothAdapter()
      if (wx.getStorageSync('timeiS')) {
        if (wx.getStorageSync('timeiS') >= 2) {
          that.showDialog({
            title: '蓝牙未响应',
            icon: 'fail',
            tip: ['请前往设置-应用内打开手机蓝牙', '请勿下拉打开蓝牙！']
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 2000)
        } else {
          wx.setStorageSync('timeiS', Number(wx.getStorageSync('timeiS')) + 1)
          that.showDialog({
            title: '蓝牙未响应',
            icon: 'fail',
            tip: ['请重新打开设备蓝牙', '并重新扫描二维码。']
          })
        }
      } else {
        wx.setStorageSync('timeiS', 1)
        that.showDialog({
          title: '蓝牙未响应',
          icon: 'fail',
          tip: ['请重新打开设备蓝牙', '并重新扫描二维码。']
        })
      }
      that.setData({
        btnFis: false
      })
      clearTimeout(trimA)
      trimA = null
      wx.hideLoading()
    }, 5000)
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success(rest) {
        wx.removeStorageSync('timeiS')
        wx.hideLoading()
        clearTimeout(trimA)
        trimA = null
        setTimeout(() => {
          that.getBLEDeviceServices(deviceId);
        }, 1000)
        wx.stopBluetoothDevicesDiscovery({
          success(res) {}
        });
      },
      fail(err) {
        wx.closeBLEConnection()
        wx.closeBluetoothAdapter()
        // console.log(trimA,'看看试试啊');
        // if(trimA){
        //   that.showDialog({
        //     title: '蓝牙访问失败',
        //     icon: 'fail',
        //     tip: ['请重新扫码']
        //   })
        // }
        // clearTimeout(trimA)
        // trimA = null
        // wx.hideLoading()
        that.setData({
          btnFis: false
        })
      }
    });
  },

  bindtapScan() {
    wx.closeBluetoothAdapter()
    let that = this
    let lock = null
    let locationEnabled = false
    let locationAuthorized = false
    let bluetoothEnabled = false
    if (!that.data.isLock) {
      that.setData({
        isLock: new Date().getTime()
      })
    } else {
      lock = new Date().getTime()
    }
    if (that.data.isLock && lock) {
      if (lock - that.data.isLock < app.globalData.isNumLock) {
        return
      } else {
        that.setData({
          isLock: lock
        })
      }
    }
    let command = []
    that.data.orderData.treatments.map(item => {
      command.push(item.treatmentId)
    })

    //激活项目指令
    let commandArr = 'AA12' + this.binaryToHex(command) + '00BBFFFFFFFFFFFFFFFFFFFFFF'
    let commandStartArr = 'AA11' + that.timeToHex(that.data.orderData.projectOfDays, that.data.orderData.treatmentOfDays) + 'DCFFFFFFFFFFFFFFFFFFFFFF'
    that.setData({
      commandEnd: commandArr,
      commandStart: commandStartArr
    })
    that.setData({
      btnFis: true
    })
    wx.getSystemInfo({
      success(resd) {
        console.log(resd, '设备');
        locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
        locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
        bluetoothEnabled = resd.bluetoothEnabled; //判断蓝牙服务是否开启
        if (!locationEnabled) {
          that.showDialog({
            title: '手机未打开定位功能',
            icon: 'fail',
            tip: ['']
          })
          wx.closeBluetoothAdapter()
          that.setData({
            btnFis: false
          })
        } else if (!locationAuthorized) {
          that.showDialog({
            title: '微信未授权定位权限',
            icon: 'fail',
            tip: ['请前往设置-应用内打开', '微信定位信息权限']
          })
          wx.closeBluetoothAdapter()
          that.setData({
            btnFis: false
          })
        } else if (!bluetoothEnabled) {
          that.showDialog({
            title: '手机蓝牙未打开',
            icon: 'fail',
            tip: ['请前往设置-应用内打开', '手机蓝牙']
          })
          wx.closeBluetoothAdapter()
          that.setData({
            btnFis: false
          })
        } else {
          wx.getSetting({
            success: res => {
              console.log(res);
              let authSetting = res.authSetting
              if (authSetting['scope.userLocation']) {
                if (authSetting['scope.bluetooth']) {

                  wx.scanCode({
                    onlyFromCamera: true,
                    success: (resCode) => {
                      console.log(resCode);
                      if (resCode.errMsg == "scanCode:ok") {
                        console.log(resCode, '扫码内容');
                        if (!resCode.result.match(RegExp(/便携式低频脉冲治疗仪/))) {
                          that.showDialog({
                            title: '无效二维码',
                            icon: 'fail',
                            tip: ['请扫描设备背部二维码']
                          })
                          that.setData({
                            btnFis: false
                          })
                          return
                        }
                        let A = resCode.result.indexOf(';')
                        let B = resCode.result.indexOf(';', A + 1)
                        let deviceNo = resCode.result.substring(A + 1, B)
                        wx.request({
                          url: app.globalData.serverUrl + '/device/check/' + deviceNo,
                          method: 'GET',
                          header: {
                            'token': wx.getStorageSync('token')
                          },
                          success: (resdeviceNo => {
                            if (resdeviceNo.data.code == 200) {
                              let newYCL = resCode.result.slice(0, resCode.result.indexOf(';'))
                              wx.setStorageSync('chb_key', that.addObjret(newYCL));
                              that.setData({
                                BTLTEST: that.addObjret(newYCL),
                                deviceNo: deviceNo,
                                orderNo: that.data.orderData.orderNo
                              })
                              if (that.data.modelid == 'iPhone') {
                                that.startBluetoothDeviceDiscovery()
                              } else {
                                console.log('’33333333');
                                wx.openBluetoothAdapter({
                                  success: (res) => {
                                    console.log(res);
                                    //已打开
                                    wx.getBluetoothAdapterState({
                                      //蓝牙的匹配状态
                                      success: (res1) => {
                                        console.log(res1, "本机设备的蓝牙已打开");
                                        //生成密钥存储
                                        let keys;
                                        keys = wx.getStorageSync('chb_key').split(':')
                                        wx.setStorageSync('key_K', that.keysfun(keys))
                                        that.setData({
                                          deviceId: wx.getStorageSync('chb_key')
                                        })
                                        wx.setStorageSync('deviceId', wx.getStorageSync('chb_key'))
                                        that.createBLEConnection(wx.getStorageSync('chb_key'))
                                      },
                                      fail(error) {
                                        that.showDialog({
                                          title: '手机蓝牙未打开',
                                          icon: 'fail',
                                          tip: ['请前往设置-应用内打开', '手机蓝牙']
                                        })
                                        that.setData({
                                          btnFis: false
                                        })
                                      },
                                    });
                                  },
                                  fail: (err) => {
                                    console.log(err);
                                    that.showDialog({
                                      title: '手机蓝牙未打开',
                                      icon: 'fail',
                                      tip: ['请前往设置-应用内打开', '手机蓝牙']
                                    })
                                    that.setData({
                                      btnFis: false
                                    })
                                  }
                                })

                              }
                            } else if (resdeviceNo.data.code == 5016) {
                              that.showDialog({
                                title: '该设备已出租',
                                icon: 'fail',
                                tip: ['请将设备归还后在进行配置']
                              })
                              that.setData({
                                btnFis: false
                              })
                              wx.closeBluetoothAdapter()
                            } else if (resdeviceNo.data.code == 5012) {
                              that.showDialog({
                                title: '该设备已损坏',
                                icon: 'fail',
                                tip: ['请联系厂家维修设备']
                              })
                              that.setData({
                                btnFis: false
                              })
                              wx.closeBluetoothAdapter()
                            } else if (resdeviceNo.data.code == 5015) {
                              that.showDialog({
                                title: '非本科室设备',
                                icon: 'fail',
                                tip: ['非本科室设备无法', '进行任何操作']
                              })
                              that.setData({
                                btnFis: false
                              })
                              wx.closeBluetoothAdapter()
                            } else if (resdeviceNo.data.code == 5013) {
                              that.showDialog({
                                title: resdeviceNo.data.message,
                                icon: 'fail',
                                tip: ['']
                              })
                              that.setData({
                                btnFis: false
                              })
                              wx.closeBluetoothAdapter()
                            } else {
                              if (resdeviceNo.data.message.indexOf(',')) {
                                let arr = resdeviceNo.data.message.split(',')
                                let arr1 = []
                                arr.map((item, index) => {
                                  if (index != 0) {
                                    arr1.push(item)
                                  }
                                })
                                that.showDialog({
                                  title: arr[0],
                                  icon: 'fail',
                                  tip: [arr1]
                                })
                                that.setData({
                                  btnFis: false
                                })
                                wx.closeBluetoothAdapter()
                              } else {
                                that.showDialog({
                                  title: resdeviceNo.data.message,
                                  icon: 'fail',
                                  tip: ['']
                                })
                                that.setData({
                                  btnFis: false
                                })
                                wx.closeBluetoothAdapter()
                              }
                            }
                          })
                        })
                      } else {
                        that.setData({
                          btnFis: false
                        })
                        app.showMsg('无效二维码!')
                      }
                    },
                    fail() {
                      that.setData({
                        btnFis: false
                      })
                    }
                  })
                } else {
                  that.showDialogsq({
                    title: '请授权蓝牙权限',
                    icon: 'warning',
                    tip: ['']
                  })

                }
              } else {
                that.showDialogsq({
                  title: '请给予微信定位权限',
                  icon: 'warning',
                  tip: ['']
                })
                that.setData({
                  btnFis: false
                })
              }
            }
          })
        }

      },
      fail() {
        that.showDialog({
          title: '手机未打开定位功能',
          icon: 'fail',
          tip: ['']
        })
        that.setData({
          btnFis: false
        })
      }
    })
    // wx.navigateTo({
    //   url: '/pages/equipment/addzg/addzg?ovData=' + JSON.stringify(newData),
    // })
  },

  //设备指令 蓝牙数据
  startBluetoothDeviceDiscovery() {
    let that = this;
    let deviceId = ''
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log(res);
        //已打开
        wx.getBluetoothAdapterState({
          //蓝牙的匹配状态
          success: (res1) => {
            console.log(res1, "本机设备的蓝牙已打开");
            //生成密钥存储
            console.log('开始搜索蓝牙设备')
            wx.startBluetoothDevicesDiscovery({
              success: (res) => {
                console.log(res, '搜索到的设备');
                // // 发现外围设备
                wx.showLoading({
                  title: '设备搜索中',
                  mask: true
                })
                that.getDeviceId().then(response => {
                  console.log(response, '查看返回值');
                  if (response == undefined) {
                    that.showDialog({
                      title: '设备蓝牙未打开',
                      icon: 'fail',
                      tip: ['请检查设备蓝牙是否打开；', '设备电量是否充足。']
                    })
                    wx.closeBluetoothAdapter()
                    return
                  }
                  //生成密钥存储
                  let keys;
                  keys = response.newdeviceId.split(':')
                  wx.setStorageSync('key_K', that.keysfun(keys))
                  that.setData({
                    deviceId: response.deviceId,
                    btnFis: false
                  })
                  try {
                    wx.setStorageSync('deviceId', that.data.deviceId)
                  } catch (e) {
                    //TODO handle the exception
                  }
                  deviceId = response.deviceId;
                  if (deviceId) {
                    wx.createBLEConnection({
                      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                      deviceId,
                      success(rest) {
                        wx.hideLoading()
                        setTimeout(() => {
                          that.getBLEDeviceServices(deviceId);
                        }, 1000)
                        wx.stopBluetoothDevicesDiscovery({
                          success(res) {}
                        });
                      },
                      fail(err) {
                        console.log(err);
                      }
                    });
                  }
                })
              }
            })
          },
          fail(error) {
            console.log(error);
            that.showDialog({
              title: '手机蓝牙未打开',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '手机蓝牙']
            })
            that.setData({
              btnFis: false
            })
          },
        });
      },
      fail: (err) => {
        console.log(err);
        that.showDialog({
          title: '手机蓝牙未打开',
          icon: 'fail',
          tip: ['请前往设置-应用内打开', '手机蓝牙']
        })
        that.setData({
          btnFis: false
        })
      }
    })

  },
  //密钥生成
  keysfun(data) {
    let that = this
    let strs = '545a5a59' + data.join('')
    data.map((item, index) => {
      let F = parseInt(('0x' + item)) + parseInt(('0x0' + (index + 1)))
      strs += F.toString(16)
    })
    return strs
  },
  getBLEDeviceServices(deviceId) {
    let that = this;
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success: (res) => {
        console.log(res, '连接成功返回值');
        wx.onBLEConnectionStateChange(function (res) {
          // 该方法回调中可以用于处理连接意外断开等异常情况
          if (!res.connected) {
            that.showDialog({
              title: '蓝牙已断开',
              icon: 'fail',
              tip: ['请重新扫码连接']
            })
            wx.offBLEConnectionStateChange()
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 2000)
          }
        })
        if (res.services) {
          let resA = res.services
          res.services.map((item, index) => {
            if (item.isPrimary) {
              wx.getBLEDeviceCharacteristics({
                deviceId,
                serviceId: item.uuid,
                success: (resServe) => {
                  console.log(resServe, '蓝牙服务');
                  resServe.characteristics.map(vtm => {
                    if (vtm.uuid == '0000FFF6-0000-1000-8000-00805F9B34FB') {
                      that.setData({
                        UUID1: resA[index].uuid,
                        UUID2: vtm.uuid
                      })
                      try {
                        wx.setStorageSync('UUID1',
                          that.data.UUID1)
                        wx.setStorageSync('UUID2',
                          that.data.UUID2)
                      } catch (e) {
                        //TODO handle the exception
                      }
                      that.notifyBLECharacteristicValueChange(
                        deviceId, that.data.UUID1,
                        that.data.UUID2, true);
                    }
                  })
                }
              })
              console.log(item.uuid, '设备UUID');
            }
          })

        }
      }
    })
  },
  // 向蓝牙写入数据
  BleWrite(instruction, characteristicIdA, serviceIdA) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let _this = this
    _this.setData({
      type: 1
    })
    // let serviceId = _this.serviceId
    let serviceId = serviceIdA;
    let characteristicId = characteristicIdA;
    let deviceId = _this.data.deviceId
    // const buffer = _this.hexStringToArrayBuffer(instruction);
    // const buffer = _this.hexStringToArrayBuffer1(instruction);
    const buffer = _this.hex2ArrayBuffer(instruction);
    console.log('buffer=======================', buffer)
    wx.writeBLECharacteristicValue({
      deviceId, // 蓝牙设备 deviceId
      serviceId, // 蓝牙服务uuid,即第二个uuid
      characteristicId, // 蓝牙特征值的 (即 writeId)
      value: buffer, // 这里的value是ArrayBuffer类型
      success(res) {
        console.log('指令下发成功==', res.errMsg, res)
        console.log('指令下发成功传入的参数--characteristicId', characteristicId, '--serviceId：',
          serviceId)
        wx.readBLECharacteristicValue({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
          deviceId: deviceId,
          // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取  
          serviceId: serviceId,
          // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取  
          characteristicId: characteristicId,
          success: (res) => {
            console.log('readBLECharacteristicValue:success', res)
          },
          fail: (res) => {
            console.log('readBLECharacteristicValue:fail', res)
          }
        })
      },
      fail(err) {
        console.log('写入数据失败', err)
        console.log('指令下发失败传入的参数--characteristicId', characteristicId, '--serviceId：',
          serviceId)
        wx.showToast({
          icon: "none",
          title: "请确保您的手机已连接设备",
          duration: 3000
        })
      }
    })
  },
  //监听开始和取消
  async notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId, state) {
    let that = this;
    wx.notifyBLECharacteristicValueChange({
      state: state, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      success(res) {
        that.BleWrite(encryptionData(that.data.commandStart, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
        wx.showLoading({
          title: '正在充值...',
          mask: true
        })
        console.log(res, '监听的值看看');
        if (!state) {
          that.notifyBLECharacteristicValueChange(that.data.deviceId, that.data.serviceId, that.data
            .characteristicId, true);
        }
        wx.onBLECharacteristicValueChange(
          function (resa) {
            if (that.data.type == 1) {
              let a = that.buf2hex(resa.value)
              // console.log('监听成功1', a, '----', that.ab2hex(resa.value))
              let successAC = decryptData(a, wx.getStorageSync('key_K')).substr(0, 8)
              console.log(successAC, '成功截取');
              if (successAC == 'aa1101ba') {
                wx.hideLoading()
                wx.showLoading({
                  title: '正在激活...',
                  mask: true
                })
                that.BleWrite(encryptionData(that.data.commandEnd, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)

              }
              if (successAC == 'aa1102ba') {
                wx.hideLoading()
                that.showDialog({
                  title: '充值失败',
                  icon: 'fail',
                  tip: ['请重新操作']
                })
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  })
                }, 1000)
              }
              if (successAC == 'aa1201b9') {
                wx.request({
                  url: app.globalData.serverUrl + '/device/down',
                  method: 'POST',
                  header: {
                    'token': wx.getStorageSync('token')
                  },
                  data: {
                    deviceNo: that.data.deviceNo,
                    orderNo: that.data.orderNo
                  },
                  success: (res => {
                    if (res.data.code == 200) {
                      wx.offBLEConnectionStateChange()
                      wx.hideLoading({
                        success: (res) => {
                          that.showDialog({
                            title: '传输成功',
                            icon: 'success',
                            tip: ['可以使用设备进行治疗了！']
                          })
                          wx.removeStorageSync('deviceId')
                          wx.removeStorageSync('UUID1')
                          wx.removeStorageSync('UUID2')
                          wx.removeStorageSync('key_K')
                          wx.removeStorageSync('chb_key')
                          if (wx.getStorageSync('deviceId')) {
                            wx.closeBLEConnection({
                              deviceId: wx.getStorageSync('deviceId'),
                              success(res) {},
                              fail(res) {}
                            })
                          }
                          wx.closeBluetoothAdapter()
                          setTimeout(() => {
                            wx.navigateBack({
                              delta: 1,
                            })
                          }, 1500)
                        },
                      })
                    } else {
                      // AA14BEFFFFFFFFFFFFFFFFFFFFFFFFFF
                      that.BleWrite(encryptionData("AA14BEFFFFFFFFFFFFFFFFFFFFFFFFFF", wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
                    }
                  })
                })
              }
              if (successAC == 'aa1202b9') {
                wx.hideLoading()
                that.showDialog({
                  title: '激活失败',
                  icon: 'fail',
                  tip: ['请重新操作']
                })
                that.BleWrite(encryptionData("AA14BEFFFFFFFFFFFFFFFFFFFFFFFFFF", wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
              }
              if (successAC == 'aa1401bf') {
                wx.closeBluetoothAdapter()
                wx.navigateBack({
                  delta: 1,
                })
              }
            }
          }
        );
      },
      fail(err) {
        console.log('报错了1', err)
      }
    });

  },
  // 发现外围设备
  getDeviceId() {
    let that = this;
    console.log("执行到这--发现外围设备1")
    return new Promise(function (resolve, reject) {
      let deviceId;
      let timer = setTimeout(() => {
        if (!deviceId) {
          wx.closeBluetoothAdapter({
            success(res) {
              wx.hideLoading()
              console.log('清理蓝牙监听', res)
              that.showDialog({
                title: '设备蓝牙未打开',
                icon: 'fail',
                tip: ['']
              })
            }
          })
          resolve(undefined);
          clearTimeout(timer);
          timer = null
        }
      }, 5000);
      wx.onBluetoothDeviceFound(function (devices) {
        console.log('发现的设备2', devices, '-----------', that.data.BTLTEST)
        // if(wx.getStorageSync('modelid')!='当前设备是其他类型'){
        let newdeviceId = that.addObjretIphone(devices.devices[0].name.slice(devices.devices[0].name.indexOf(' ') + 1))
        if (newdeviceId === that.data.BTLTEST) {
          // let myTimer = setInterval(() => {

          //   clearInterval(timer);
          //   clearInterval(myTimer);
          //   return;
          // }, 1000);
          deviceId = devices.devices[0].deviceId;
          let a;
          a = {
            deviceId: devices.devices[0].deviceId,
            newdeviceId: newdeviceId
          }
          resolve(a);
          clearTimeout(timer);
          timer = null
        }
        // }else{
        //   if (devices.devices[0].deviceId == that.data.BTLTEST) {
        //     let myTimer = setInterval(() => {
        //       deviceId = devices.devices[0].deviceId;
        //       let a;
        //       a = {
        //         deviceId: deviceId,
        //       }
        //       resolve(a);
        //       clearInterval(timer);
        //       clearInterval(myTimer);
        //       return;
        //     }, 1000);
        //   }
        // }
      });
    });
  },
  // 16进制字符串转ArrayBuffer
  hex2ArrayBuffer(hex_str) {
    // let hex_str = 'AA5504B10000B5'
    let typedArray = new Uint8Array(hex_str.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    let buffer = typedArray.buffer
    return buffer
  },
  // ArrayBuffer转16进度字符串
  buf2hex(arrayBuffer) {
    return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2))
      .join('');
  },
  //处理字符
  addObjretIphone(data) {
    let result = "";
    let newarr = []
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    newarr = result.split(':')
    return newarr.reverse().join(':')
  },
  addObjret(data) {
    let result = "";
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    return result
  },
  // bit转换
  binaryToHex(binary) {
    let arrayD = ['项目治疗一', '项目治疗二', '常规催乳', '乳汁分泌少', '乳腺管不通', '子宫复旧', '产后排尿', '产后恢复']
    let bitStr = '00000000'
    binary.map(item => {
      bitStr = bitStr.substring(0, 7 - item) + '1' + bitStr.substring(7 - item + 1)
    })
    const decimal = new Number(`0b${bitStr}`);
    let hexadecimal = decimal.toString(16);
    if (hexadecimal.length == 1) {
      hexadecimal = '0' + hexadecimal
    }
    return hexadecimal.toUpperCase();
  },
  //时间转换
  timeToHex(timeDays, sum) {
    // let endTime = ''
    timeDays = Number(timeDays) * Number(sum) * 60
    let hex16 = timeDays.toString(16).toUpperCase()
    if (hex16.length % 2 == 0) {
      if (hex16.length == 2) {
        return hex16 + '00'
      }
      return hex16.substring(2) + hex16.substring(0, 2)
    } else {
      hex16 = '0' + hex16
      return hex16.substring(2) + hex16.substring(0, 2)
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */

  onShow() {
    this.setData({
      isLock: null,
      modelid: wx.getStorageSync('modelid')
    })
    wx.removeStorageSync('timeiS')
    wx.setStorageSync('isT', 1)
    wx.hideLoading()
    // wx.closeBluetoothAdapter({
    //   success(res) {},
    //   fail(res) {}
    // })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})